package cn.chinaunicom.cyhlw.web.oauthServer.conf;


import cn.chinaunicom.cyhlw.web.oauthServer.customExceptionTranslator.CustomWebResponseExceptionTranslator;
import cn.chinaunicom.cyhlw.web.oauthServer.handler.MyUserAuthenticationConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;
import java.security.KeyPair;

/**
 * Created by chenzesen on 2019/1/2.
 * <p>
 * 授权中心权限配置类，请谨慎修改
 */
@Configuration
@EnableAuthorizationServer
public class OAuthServerConfig extends AuthorizationServerConfigurerAdapter {

    Logger logger = LoggerFactory.getLogger(OAuthServerConfig.class);
    /**
     * 自定义异常处理和异常返回
     */
    @Autowired(required = false)
    CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator;


    @Autowired(required = false)
    private BCryptPasswordEncoder passwordEncoder;
//
////    @Resource("userDetailsServiceImpl")
////    UserDetailsService userDetailsService

    @Autowired(required = false)
    private AuthenticationManager authenticationManager;

    /**
     * 用于重写授权服务器返回用户给资源端或者服务器端
     */
    @Autowired(required = false)
    private MyUserAuthenticationConverter myUserAuthenticationConverter;

    /**
    * 注入redis 工厂
     */
    @Autowired
    private RedisConnectionFactory connectionFactory;

//    @Autowired(required = false)
//    private DataSource dataSource;

    /**
     * 自定义实现将token 存储在redis 中，也可以存在数据中，有默认的表结构
     * @return
     */
    @Bean
    public RedisTokenStore tokenStore() {
        return new RedisTokenStore(connectionFactory);
    }

//    @Bean("jdbcTokenStore")
//    public JdbcTokenStore getJdbcTokenStore() {
//        return new JdbcTokenStore(dataSource);
//    }

//    @Bean
//    public JwtAccessTokenConverter jwtAccessTokenConverter() {
//        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
//        KeyPair keyPair = new KeyStoreKeyFactory(
//                new ClassPathResource("keystore.jks"), "foobar".toCharArray())
//                .getKeyPair("test");
//        converter.setKeyPair(keyPair);
//        return converter;
//    }

//    @Bean // 声明 ClientDetails实现
//    public ClientDetailsService clientDetailsService() {
//        return new JdbcClientDetailsService(dataSource);
//    }



    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
              //  .checkTokenAccess("isAuthenticated()")
//                .sslOnly()
                .allowFormAuthenticationForClients(); //允许客户端验证，用于开启客户端模式

    }

    /*认证的客户端信息配置*/
    @Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
        //sso存储在内存中的授权码模式 和  //存储在redis 的授权码模式 和 jdbc 存储模式
        /**----------通过数据库配置客户端信息--------*/
//         clients.withClientDetails(clientDetailsService());
        /**----------通过内存配置客户端信息--------*/
        //clients.jdbc(dataSource).w
//        String finalPassword = "{bcrypt}"+passwordEncoder.encode("123456");
        String finalPassword = passwordEncoder.encode("123456");
        logger.info("123456: {}",finalPassword);
        clients.inMemory()
                .withClient("client_1") // clientId, 可以类比为用户名
                .secret(finalPassword) // secret， 可以类比为密码
                .authorizedGrantTypes("password", "refresh_token")   // 授权类型，这里选择授权码
                .scopes("server") // 授权范围
                .autoApprove(true) // 自动认证不然会多谈一个选择认证权限的页面
//                .redirectUris("http://10.10.37.142:8082/login","http://10.10.37.142:8083/login","http://10.10.37.142:8880/linkcall/login")  // 认证成功重定向URL 这里要包含作用域，用来控制单点登录的安全很重要
                .accessTokenValiditySeconds(1000) // 超时时间，10000s
                .authorities("oauth2")
                 //客户端模式可以用来客户端间api接口调用的验证 获取toke url auth/oauth/token?grant_type=client_credentials&client_id=client_ihk&client_secret=123456
                .and().
                withClient("client_2")
                .authorizedGrantTypes("authorization_code","refresh_token")
                .scopes("all","read", "write")
//                .authorities("client_credentials")
                .secret(finalPassword)
                .accessTokenValiditySeconds(7200)
                .authorities("oauth2")
                .and()
                .withClient("client_3") // clientId, 可以类比为用户名
                .secret(finalPassword) // secret， 可以类比为密码
                .authorizedGrantTypes("client_credentials", "refresh_token")   // 授权类型，这里选择授权码
                .scopes("user_info") // 授权范围
                .autoApprove(true) // 自动认证不然会多谈一个选择认证权限的页面
//                .redirectUris("http://10.10.37.142:8082/login","http://10.10.37.142:8083/login","http://10.10.37.142:8880/linkcall/login")  // 认证成功重定向URL 这里要包含作用域，用来控制单点登录的安全很重要,带上授权码
                .accessTokenValiditySeconds(1000) // 超时时间，10000s
                .authorities("oauth2");

    }

    /**
     * 配置redis 或者jdbc存储token
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        DefaultAccessTokenConverter defaultAccessTokenConverter=new DefaultAccessTokenConverter();
        defaultAccessTokenConverter.setUserTokenConverter(myUserAuthenticationConverter); //用于重写授权服务器返回用户给资源端或者服务器端
        //端点支撑get请求
        endpoints
                .authenticationManager(authenticationManager)
//        .tokenStore(getJdbcTokenStore())  //// refresh_token需要userDetailsService
//         .userDetailsService(userDetailsServiceImpl)
        .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        endpoints.tokenServices(defaultTokenServices()).accessTokenConverter(defaultAccessTokenConverter);
        //添加自定义异常处理
      //  endpoints.exceptionTranslator(customWebResponseExceptionTranslator);

    }



        /**
         * <p>注意，自定义TokenServices的时候，需要设置@Primary，否则报错，</p>
         * @return
         */
    @Primary
    @Bean
    public DefaultTokenServices defaultTokenServices(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setSupportRefreshToken(true);
//        tokenServices.setClientDetailsService(clientDetailsService());
        tokenServices.setAccessTokenValiditySeconds(60*60*12); // token有效期自定义设置，默认12小时
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);//默认30天，这里修改

        return tokenServices;
    }

}
